<?php
/**
 * 验证码
 */
class Code
{
	public $configs =[
		'width'=>200,
		'heigth'=>100,
		'length'=>4,
		'font_size'=>50,
		'line'=>10,
		'bgColor'=>[255,255,255],
		'is_disturb'=>true,
		'point'=>20,
		'str'=>"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"
	];
	/**
	 * [__construct 构造函数]
	 * @param array $configs [验证码配置]
	 */
	public function __construct($configs=[])
	{
		$this->configs= array_merge($this->configs,$configs);
	}
	/**
	 * [entry 验证码生成方法]
	 * @return [type] [不有返回值]
	 */
	public function entry()
	{
		// 创建画布
		$this->create_bg();
		// 填充背景
		$this->fill();
		// 画点
		$this->point();
		// 画线
		$this->line();
		// 画干扰
		$this->disturb();
		// 画文字
		$this->fonts();

		$this->out();
		// 发头部声明
		// 输出 
	}

	public function __get($name)
	{
		return $this->configs[$name];
	}

	protected function create_bg()
	{
		$this->src = imageCreateTrueColor($this->width,$this->heigth);

	}

	protected function fill()
	{
		$color = imageColorAllocate($this->src,$this->bgColor[0],$this->bgColor[1],$this->bgColor[2]); 

		imageFill($this->src,0,0,$color);
		
	}
	protected function point()
	{
		for ($i=0; $i <$this->point ; $i++) { 
			$color = $this->get_color();

			imagesetpixel ($this->src , mt_rand(0,$this->width), mt_rand(0,$this->heigth) ,$color );
		}
	}
	/**
	 * [get_color 生成颜色]
	 * @param  integer $min [最小范围值]
	 * @param  integer $max [最大范围值]
	 * @return [type]       [颜色]
	 */
	protected function get_color($min=0,$max=255)
	{
		return imageColorAllocate($this->src,mt_rand($min,$max),mt_rand($min,$max),mt_rand($min,$max));
	}
	protected function line()
	{
		for ($i=0; $i <$this->line ; $i++) { 
			$color = $this->get_color();

			imageline ($this->src , mt_rand(0,$this->width), mt_rand(0,$this->heigth),mt_rand(0,$this->width), mt_rand(0,$this->heigth) ,$color );
		}
	}
	/**
	 * [disturb description]
	 * @return [type] [description]
	 */
	protected function disturb()
	{

		if($this->is_disturb){

			for ($i=0; $i <50 ; $i++) {

				$s = $this->str[mt_rand(0,strlen($this->str)-1)]; 

				$color = $this->get_color(155,255);

				imagettftext ($this->src,$this->font_size/3, mt_rand(0,360), mt_rand(0,$this->width),mt_rand(0,$this->heigth),$color , LIB_PATH.'/BOOKPB.TTF', $s);
			}
		}
		
	}
	/**
	 * [fonts description]
	 * @return [type] [description]
	 */
	protected function fonts()
	{
		for ($i=0; $i <$this->length ; $i++) { 
			
			$s = $this->str[mt_rand(0,strlen($this->str)-1)]; 

			$color = $this->get_color(0,100);

			$x = (($this->width/$this->length)-$this->font_size)/2+($this->width/$this->length)*$i;

			$y = ($this->heigth+$this->font_size)/2;


			imagettftext ($this->src,$this->font_size , mt_rand(-15,15), $x,$y  ,  $color , LIB_PATH.'/BOOKPB.TTF', $s);
		}
	}
	/**
	 * [out description]
	 * @return [type] [description]
	 */
	protected function out()
	{
		header("Content-type: image/jpeg");
		imagejpeg($this->src); 
		imageDestroy($this->src);
	}
}
